<template>
  <a-modal
    :open="open"
    width="1300px"
    title="退单"
    centered
    ok-text="保存"
    :ok-button-props="{ disabled: selectedRowKeys.length <= 0 }"
    @ok="onOk"
    @cancel="onCancel"
  >
    <div class="w-full h-18 patient-info-header py-2 px-3 flex items-center mb-4 justify-between">
      <div class="flex items-center">
        <a-avatar :size="48" :src="avatarMan" />
        <div class="text-xl font-semibold max-w-28 min-w-20 truncate text-white ml-4">
          {{ rowData?.brName || '姓名' }}
        </div>
        <div class="text-white">
          <span class="ml-4 mr-4">{{ rowData?.brXb || '性别' }}</span>
          <span class="ml-4">{{ rowData?.brAge ? rowData?.brAge : '年龄' }}</span>
        </div>
        <div class="text-white ml-6 mr-38">{{ rowData?.brMob }}</div>
      </div>
      <div class="flex items-center mr-10">
        <LabelValue label="应收金额" :width="200" label-class="text-white font-bold" value-class="text-white" :value="formatAmount(rowData.totalAmount)" />
        <LabelValue label="实付金额" :width="200" label-class="text-white font-bold" value-class="text-white" :value="formatAmount(rowData.orderAmount)" />
        <LabelValue label="实退金额" :width="200" label-class="text-white font-bold" value-class="text-white" :value="formatAmount(rowData.chargeBackAmount)" />
      </div>
    </div>
    <div class="w-full flex justify-between mb-4">
      <BaseTable
        :data-source="tableData"
        row-key="xsdmxid"
        :row-selection="{
          checkStrictly: false,
          selectedRowKeys: selectedRowKeys,
          onChange: (val) => onSelectChange(val),
          getCheckboxProps: (record) => ({
            disabled: record.status !== '1'
          })
        }"
        :row-class-name="(record) => (record.status !== '1' ? 'disabled-row' : '')"
        height="400"
        :loading="loading"
        :scroll="{ x: 1200 }"
        column-code="000427"
        :pagination="pagination"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'isOutside'">
            <span v-if="record.isOutside == 1">是</span>
            <span v-else>否</span>
          </template>
          <template v-if="column.dataIndex == 'eyesType'">
            <span v-if="record.eyesType == '1'">左眼</span>
            <span v-else-if="record.eyesType == '2'">右眼</span>
            <span v-else-if="record.eyesType == '3'">其他</span>
            <span v-else>/</span>
          </template>
          <template v-if="column.dataIndex === 'payItemName'">
            <MedicineInfo :value="{ mc: record.payItemName, gg: record.specification }" />
          </template>
          <template v-if="column.dataIndex === 'num'">
            <span>{{ record.num }}</span
            ><span class="text-gray-400 ml-2 text-xss">{{ record.unit }}</span>
          </template>
          <template v-if="column.dataIndex === 'chargeBackAmount'">
            <a-input :value="formatAmount(record.chargeBackAmount)" disabled />
          </template>
          <template v-if="column.dataIndex === 'chargeBackWarehouse'">
            <a-switch v-model:checked="record.chargeBackWarehouse" :checked-value="'1'" :un-checked-value="'0'" />
          </template>
        </template>
      </BaseTable>
    </div>
    <a-form :model="formState" class="form-style-flex">
      <a-form-item label="可退金额" class="w-1/4">
        <span class="text-red-500">￥{{ formatAmount(allMoney) }}</span>
      </a-form-item>
      <a-form-item label="退款金额" class="w-1/4">
        <span class="text-red-500">￥{{ formatAmount(refundPrice) }}</span>
      </a-form-item>
      <a-form-item label="退单备注" class="w-full">
        <a-textarea v-model:value="formState.memo" :rows="3" placeholder="请输入" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script setup>
import { ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import { formatAmount } from '@/utils/format.js'
import { post } from '@/utils/request'
import avatarMan from '@/assets/images/avatar-man.png'

const emit = defineEmits(['update:open', 'ok'])
const props = defineProps({
  open: {
    type: Boolean,
    default: false
  },
  rowData: {
    type: Object,
    default: () => ({})
  }
})
const tableData = ref([])
const selectedRowKeys = ref([])
const allMoney = ref(0)
const ids = ref([])
const refundPrice = ref(0)
const loading = ref(false)
const formState = ref({
  processName: '',
  inspectorName: '',
  summary: '',
  memo: ''
})
const rulesState = ref({})
const { resetFields } = useForm(formState, rulesState)
watch(() => {
  if (props.open) {
    getData()
  }
})
const getData = async () => {
  loading.value = true
  const { data, code } = await post('/optometry/ooadolescentcheck/getOoOpticianChargeMxResponse', {
    pjhm: props.rowData.pjhm
  })
  loading.value = false
  if (code === 0) {
    tableData.value = data
    allMoney.value = 0
    refundPrice.value = 0
    selectedRowKeys.value = []
    if (tableData.value && tableData.value.length > 0) {
      tableData.value.forEach((item) => {
        item.chargeBackAmount = item.payAmount
        item.chargeBackWarehouse = '0'
        // 状态1：正常 2：作废 3：已退费
        if (item.status === '1') {
          allMoney.value += item.payAmount ? Number(item.payAmount) : 0
          selectedRowKeys.value.push(item.xsdmxid)
          refundPrice.value += item.payAmount ? Number(item.payAmount) : 0
        }
      })
    }
  }
}
const onSelectChange = (val) => {
  selectedRowKeys.value = val
  refundPrice.value = 0
  allMoney.value = 0
  tableData.value.forEach((item) => {
    if (selectedRowKeys.value.indexOf(item.xsdmxid) > -1) {
      refundPrice.value += item.payAmount ? Number(item.payAmount) : 0
      allMoney.value += item.payAmount ? Number(item.payAmount) : 0
    }
  })
}
const onCancel = () => {
  emit('update:open', false)
  resetFields()
}

const onOk = async () => {
  const arr = []
  let obj = {}
  ids.value = []
  tableData.value.forEach((item) => {
    obj = {}
    if (selectedRowKeys.value.indexOf(item.xsdmxid) > -1) {
      obj.chargeBackAmount = item.payAmount ? Number(item.payAmount) : 0
      obj.chargeBackWarehouse = item.chargeBackWarehouse
      obj.id = item.id
      obj.xsdmxid = item.xsdmxid
      arr.push(obj)
    }
    ids.value.push(item.id)
  })
  const { code, msg } = await post('/optometry/ooadolescentcheck/doSaveOoOpticianCharge', {
    memo: formState.value.memo,
    list: arr,
    ids: ids.value
  })
  if (code === 0) {
    message.success(msg || '保存成功')
    onCancel()
    emit('ok')
  }
}
</script>
<style lang="less" scoped>
.right-border-pro {
  border: 1px solid var(--primary-color);
  border-radius: 4px;
}
.patient-info-header {
  background-color: var(--primary-color);
  border-radius: 3px;
}
</style>
